define(["jquery","bootstrap","ztree","bbcare","fu/app/comm/comm",
	"scprit/nutrition/app/courseLibrary/editCourseLibrary.ui.js",
    "scprit/nutrition/app/courseLibrary/editCourseLibrary.servers.js"
    ],function($,$bootstrap,$ztree,$bb,$comm,$ui,$servers){
	var event = {};

	var ajaxCourseLibirayDelCallBack = function(data){
		$bb.openPage("courseLibrary");
	}

	/**
	 * 删除疗程库
	 */
	event.onCourseLibirayDel = function(){
		var libraryId = $("#courseLibirayTab select").val();
		var params = {
			"libraryId":libraryId,
			"callback":ajaxCourseLibirayDelCallBack
		}
		$bb.toastConfirmShow($servers.ajaxCourseLibirayDel,params,"您确定删除该疗程库吗？");
	}

	/**
	 * 疗程标准元素添加成功后的回调函数
	 */
	var ajaxNutrienTelementModifyCallBack = function(data,courseVersionId,className){
		$("." + className).modal("hide");
		$servers.ajaxCourseNutrients(courseVersionId,ajaxCourseNutrientsCallBack);
	}

	/**
	 * 添加疗程营养元素
	 */
	var onSaveCourseNutrient = function(){
		var courseVersionId = $(this).data("courseVersionId");
		var $box = $(this).parents("form.add-course-nutrients");
		var nutrientsId = $box.find("select[name=name]").val();
		var recommendedDose = $box.find("input[name=recommendedDose]").val();
		var minIntake = $box.find("input[name=minIntake]").val();
		var maxIntake = $box.find("input[name=maxIntake]").val();
		var className = $(this).data("className");
		var params = {
			"nutrientsId":nutrientsId,
		    "courseVersionId":courseVersionId,
		    "maxAmount":maxIntake,
		    "minAmount":minIntake,
		    "averageAmount":recommendedDose,
		}
		$servers.ajaxNutrienTelementModify(params,ajaxNutrienTelementModifyCallBack,className);
	}

	/**
	 * niut跟随name的变化而相应变化
	 */
	var onNutrientsChange = function(){
		var unit = $(this).find("option:selected").attr("nutrientsUnit");
		$(this).parents("form").find("p[name=unit]").html(unit);
	}

	/**
	 * 食物营养成分字典列表成功后的回调函数
	 */
	var ajaxNutrientDictQueryCallBack = function(data,courseVersionId){
		var className = "addNodeModal";
		$comm.modal({
			"className":className,
			"tit":"添加疗程营养元素"
		},function(){
			$ui.addCourseNutrientsInit({
				"dom":$("." + className + " .modal-body"),
				"list":data
			});
			$("." + className).modal("show");
			$("form.add-course-nutrients select[name=name]").change(onNutrientsChange);
			$("form.add-course-nutrients select[name=name]").change();
			$("#addCourseNutrientsBtn").unbind("click");
			$("#addCourseNutrientsBtn").data({"courseVersionId":courseVersionId,"className":className});
			$("#addCourseNutrientsBtn").click(onSaveCourseNutrient);
		});
	}

	/**
	 * 点击添加疗程营养元素,请求食物营养成分字典列表
	 */
	var onAddCourseNutrients = function(){
		var courseVersionId = $(this).data("courseVersionId");
		$servers.ajaxNutrientDictQuery(courseVersionId,ajaxNutrientDictQueryCallBack);
	}

	/**
	 * 请求删除疗程营养元素成功后的回调函数
	 */
	var ajaxNutrienTelementDelCallBack = function(data,courseVersionId){
		$servers.ajaxCourseNutrients(courseVersionId,ajaxCourseNutrientsCallBack);
	}

	/**
	 * 删除疗程营养元素
	 */
	var onDelCourseNutrients = function(){
		var courseNutrientId = $(this).attr("courseNutrientId");
		var courseVersionId = $(this).attr("courseVersionId");
		var params = {
			"courseVersionId":courseVersionId,
			"courseNutrientId":courseNutrientId,
			"callback":ajaxNutrienTelementDelCallBack
		}
		$bb.toastConfirmShow($servers.ajaxNutrienTelementDel,params,"确定删除该疗程营养元素吗？");
	}

	/**
	 * 修改疗程营养元素成功后的回调函数
	 */
	var ajaxNutrienDoseModifyCallBack = function(data,courseVersionId){
    	$servers.ajaxCourseNutrients(courseVersionId,ajaxCourseNutrientsCallBack);
    }

	/**
	 * 失去焦点后请求保存疗程营养元素的修改值
	 */
	var onBlurCourseNutrients = function(){
		var value = $(this).val();
		var courseNutrientId = $(this).parent("td").attr("courseNutrientId");
		var courseVersionId = $(this).parent("td").attr("courseVersionId");
		var nutrientsId = $(this).parent("td").attr("nutrientsId");
		var name = $(this).parent("td").attr("name");
		var params = {
			"nutrientsId":nutrientsId,
		    "courseNutrientId":courseNutrientId,
		    "courseVersionId":courseVersionId,
	    }
	    if(name == "averageAmount"){
	    	params = $.extend(params,{"averageAmount":value});
	    }else if(name == "maxAmount"){
	    	params = $.extend(params,{"maxAmount":value});
	    }else if(name == "minAmount"){
	    	params = $.extend(params,{"minAmount":value});
	    }
	    $servers.ajaxNutrienTelementModify(params,ajaxNutrienDoseModifyCallBack);
	}

	/**
	 * 修改疗程营养元素
	 */
	var onDblclickCourseNutrients = function(){
		if( $(this).find("input").length == 0 ){
			var str = $(this).text();
			var h = '<input type="number" min="0" value="'+ str +'">';
			$(this).html(h);
		}
		$(this).find("input").unbind("blur");
		$(this).find("input").blur(onBlurCourseNutrients);
	}

	/**
	 * 保存时段成功后的回调函数
	 */
	var ajaxCoursePeriodModifyCallBack = function(data,courseVersionId){
		$servers.ajaxCourseNutrients(courseVersionId,ajaxCourseNutrientsCallBack,true);
	}

	/**
	 * 保存时段
	 */
	var onSavePeriod = function(){
		var courseVersionId = $(this).data("courseVersionId");
		var $li = $(this).parents("li");
		var periodName = $li.find(".period-name input").val();
		var periodId = $li.attr("periodId");
		var startTimeHours = $li.find("select.startTime-hours").val();
		var startTimeMin = $li.find("select.startTime-min").val();
		var endTimeHours = $li.find("select.endTime-hours").val();
		var endTimeMin = $li.find("select.endTime-min").val();
		var startTime = Number(startTimeHours*60) + Number(startTimeMin);
		var endTime = Number(endTimeHours*60) + Number(endTimeMin);
		var params = {
			"courseVersionId":courseVersionId,
			"startTime":startTime.toString(),	
		    "endTime":endTime.toString(),
		    "periodName":periodName,
		    "periodId":periodId
		}
		$servers.ajaxCoursePeriodModify(params,courseVersionId,ajaxCoursePeriodModifyCallBack);
	}

	/**
	 * 删除时段成功后的回调函数
	 */
	var ajaxCoursePeriodRemoveCallBack = function(data,courseVersionId){
		$servers.ajaxCourseNutrients(courseVersionId,ajaxCourseNutrientsCallBack,true);
	}

	/**
	 * 删除时段
	 */
	var onDelPeriod = function(){
		var courseVersionId = $(this).data("courseVersionId");
		var periodId = $(this).parents("li").attr("periodId");
		var _this = this;
		var delPeriodFn = function(){
			if(periodId){
				$servers.ajaxCoursePeriodRemove(periodId,courseVersionId,ajaxCoursePeriodRemoveCallBack);
			}else{
				$(_this).parents("li").remove();
			}
		};
		$bb.toastConfirmShow(delPeriodFn,"","您确定删除该时间段？");
	}

	/**
	 * 保存时段、修改时段
	 */
	var operatePeriod = function(courseVersionId){
		// 保存时段（添加、修改）
		$("#periodBox li .savePeriod").unbind("click");
		$("#periodBox li .savePeriod").data({"courseVersionId":courseVersionId});
		$("#periodBox li .savePeriod").click(onSavePeriod);
		// 删除时段
		$("#periodBox li .delPeriod").unbind("click");
		$("#periodBox li .delPeriod").data({"courseVersionId":courseVersionId});
		$("#periodBox li .delPeriod").click(onDelPeriod);
	}

	/**
	 * 添加时段
	 */
	var onAddPeriod = function(){
		var courseVersionId = $(this).data("courseVersionId");
		$ui.addCoursePeriodLiInit({
			"id":"periodBox"
		});
		operatePeriod(courseVersionId);
	}

	/**
	 * 编辑疗程时段
	 */
	var onAddCoursePeriod = function(){
		var data = $(this).data("data");
		var courseVersionId = $(this).data("courseVersionId");
		var className = "editPeriodModal";
		$comm.modal({
			"className":className,
			"tit":"编辑时段"
		},function(){
			$ui.addCoursePeriodInit({
				"dom":$("." + className + " .modal-body"),
				"list":data
			});
			$("." + className).modal("show");
			$("#addPeriod").unbind("click");
			$("#addPeriod").data({"courseVersionId":courseVersionId});
			$("#addPeriod").click(onAddPeriod);
			operatePeriod(courseVersionId);
		});
	}

	/**
	 * 保存修改的食物包装单位量和用量
	 */
	var onBlurCourseFood = function(dom){
		var value = $(dom).val();
		var courseVersionId = $(dom).parents("table").attr("courseVersionId");
		var periodId = $(dom).parents("td.dblclick-edit").siblings("td.food-name").attr("periodId");
		var courseFoodId = $(dom).parents("td.dblclick-edit").siblings("td.food-name").attr("courseFoodId");
		var foodId = $(dom).parents("td.dblclick-edit").siblings("td.food-name").attr("foodId");
		var name = $(dom).parents("td.dblclick-edit").attr("name");
		var value2 = $(dom).parents("td.dblclick-edit").siblings("td.dblclick-edit").find("span").html();
		var params = {
			"courseVersionId":courseVersionId,
			"periodId":periodId,
			"foodId":foodId,
			"courseFoodId":courseFoodId
		};
		if(name == "packageTotal"){
			params = $.extend(params,{"packageTotal":value,"total":value2});
		}else if(name == "total"){
			params = $.extend(params,{"total":value,"packageTotal":value2});
		}
		$servers.ajaxCourseFoodModify(params,ajaxCourseFoodModifyCallBack);
	};

	/**
	 * 修改食物的包装单位量和用量
	 */
	var onDblclickCourseFood = function(){
		if( $(this).find(".need-dblclick").length > 0 ){
			if( $(this).find("input").length == 0 ){
				var str = $(this).find("span").text();
				var h = '<input type="number" min="0" value="'+ str +'">';
				$(this).find("span").html(h);
				$(this).find("span > input").focus(function(){
					var foodId = $(this).parents("td.dblclick-edit").siblings("td.food-name").attr("foodId");
					if(foodId){
						editSureFoodConsumption(this);
					}
				});
				$(this).find("span> input").focus();
			}
		}
	};

	/**
	 * 删除疗程时段中的食物
	 */
	var onDelCourseFood = function(){
		var courseFoodId = $(this).parent("td.food-name").attr("courseFoodId");
		var courseVersionId = $(this).parents("table").attr("courseVersionId");
		var delFoodFn = function(){
			$servers.ajaxCourseFoodDel(courseFoodId,courseVersionId,ajaxCourseFoodModifyCallBack);
		}
		$bb.toastConfirmShow(delFoodFn,"","您确定删除此种食物？");

	}
	//弹窗：
	var editSureFoodConsumption = function(dom){
		var className = "editFoodConsumptionModal";
		var unit = $(dom).parents(".dblclick-edit").find("font.unit").html();
		var foodName = $(dom).parents("tr").find('td.food-name').attr("foodName");
		var periodName = $(dom).parents("tr").find('td.food-name').attr("periodName");
		var periodTime = $(dom).parents("tr").find('td.food-name').attr("periodTime");
		var period =  periodName+"&nbsp;" + periodTime;
		var _this = dom;
		$comm.modal({
			"className":className,
			"tit":"请输入该食物用量"
		},function(){
			$ui.foodConsumptionInit({
				"dom":$("." + className + " .modal-body"),
				"data":{"title":foodName,"periodName":period,"unit":unit,"value": $.trim($(_this).val())}
			});
			$("." + className).find("button.close").css("display",'none');
			$("." + className).modal({backdrop: "static",keyboard:false,show:true});
			$("#sureFoodConsumption").unbind("click");
			$("#sureFoodConsumption").data({"dom":_this,"className":className});
			$("#sureFoodConsumption").click(sureFoodConsumption);
		});
	}
	//获取弹窗的值
	var sureFoodConsumption = function(){
		var data = $(this).data();
		var value= $.trim($("#foodConsumption").val())*1;
		if(value <= 0){
			$bb.toastShow("请输入大于0的数值",1500);
			$("#foodConsumption").focus();
		}else{
			$("." + data.className).modal('hide');
			$(data.dom).val(value);
			onBlurCourseFood(data.dom)
		}
	};
	/**
	 * 疗程食物查询成功后的回调函数
	 */
	var ajaxCoursefoodCallBack = function(data,list,courseVersionId,flag){
		$ui.courseNutrientsInit({
			"id":"courseNutrients",
			"list":list
		});
		$ui.courseFoodInit({
			"id":"courseFood",
			"list":data,
			"courseVersionId":courseVersionId
		});
		// 添加疗程营养元素
		$("#addCourseNutrients").unbind("click");
		$("#addCourseNutrients").data({"courseVersionId":courseVersionId});
		$("#addCourseNutrients").click(onAddCourseNutrients);
		// 删除疗程营养元素
		$("#courseNutrients .course-nutrients").unbind("click");
		$("#courseNutrients .course-nutrients").click(onDelCourseNutrients);
		// 修改疗程营养元素里的剂量
		$("#courseNutrients .dblclick-edit").unbind("dblclick");
		$("#courseNutrients .dblclick-edit").dblclick(onDblclickCourseNutrients);
		// 编辑疗程时段
		$("#addCoursePeriod").unbind("click");
		$("#addCoursePeriod").data({"courseVersionId":courseVersionId,"data":data});
		$("#addCoursePeriod").click(onAddCoursePeriod);
		// 默认false不自动点击编辑时段按钮;shansh
		if(flag) $("#addCoursePeriod").click();
		// 修改食物用量
		$("#courseFood .dblclick-edit").unbind("dblclick");
		$("#courseFood .dblclick-edit").dblclick(onDblclickCourseFood);
		$("#courseFood .no-need-dblclick > input").focus(function(){
			var foodId = $(this).parents("td.dblclick-edit").siblings("td.food-name").attr("foodId");
			if(foodId){
				editSureFoodConsumption(this);
			}
		});
		$("#courseFood .no-need-dblclick > input").focus();
		// 删除疗程时段中的食物
		$("#courseFood .del-course-food").unbind("click");
		$("#courseFood .del-course-food").click(onDelCourseFood);
	}

	/**
	 * 查询疗程营养元素成功后的回调函数
	 */
	var ajaxCourseNutrientsCallBack = function(data,courseVersionId,flag){
		$servers.ajaxCoursefood(courseVersionId,ajaxCoursefoodCallBack,data,flag);
	}

	/**
	 * 疗程基本信息查询成功后的回调函数
	 */
	var ajaxCoursebasicCallBack = function(data){
		$ui.courseInfoInit({
			"id":"courseInfo",
			"data":data
		});
		var flag = false; // 默认不自动点击编辑时段按钮
		$servers.ajaxCourseNutrients(data.courseVersionId,ajaxCourseNutrientsCallBack,flag);
	}

	/**
	 * 删除（分类）
	 */
	var onRemoveCourseClassify = function(){
		$("#context-menu").removeClass("open");
		var data = $(this).data();
		var libraryId = $("#courseLibirayTab select").val();
		var params = {
			"courseTypeId":data.id
		};
		$servers.ajaxCourseTypeDel(params,function(data){
			onCourseChange(libraryId);
		});
	}
	/**
	 * 保存（分类的添加、重命名）
	 */
	var onSaveCourseClassify = function(){
		var data = $(this).data("params");
		var className = $(this).data("className");
		var libraryId = $("#courseLibirayTab select").val();
		var name = $(this).parents("form").find("input[name=name]").val();
		var remark = $(this).parents("form").find("input[name=remark]").val();
		var params = {
		    "courseTypeName":name,
		    "libraryId":libraryId,
		    "parentId":data.pId,
		    "courseTypeId":data.id
		};
		// 为了防止修改时（不修remark时），把之前填的替换掉
		if(remark && remark != "") params = $.extend(params,{"remark":remark});
		$servers.ajaxCourseTypeModify(params,function(data){
			$("." + className).modal("hide");
			onCourseChange(libraryId,data);
		});
	};

	/**
	 * 点击添加、重命名按钮（分类的添加、重命名）
	 */
	var onModifyCourseClassify = function(){
		$("#context-menu").removeClass("open");
		var data = $(this).data();
		var tit = data.classify == "1" ? "添加根分类" : data.classify == "2" ? "添加子分类" : "重命名";
		var originalName = data.classify == "3" ? data.name : "";
		var className = "addNodeModal";
		$comm.modal({
			"className":className,
			"tit":tit
		},function(){
			$ui.modifyCourseClassifyFormInit({
				"dom":$("." + className + " .modal-body"),
				"name":originalName
			});
			$("." + className).modal("show");
			$("#modifyCourseClassifyBtn").unbind("click");
			$("#modifyCourseClassifyBtn").data({"params":data,"className":className});
			$("#modifyCourseClassifyBtn").click(onSaveCourseClassify);
		});
	};

	/**
	 * 添加疗程、重命名疗程保存成功后的回调函数
	 */
	var saveCourseCallBack = function(data,libraryId,className){
		$("." + className).modal("hide");
		onCourseChange(libraryId,data);
	}

	/**
	 * 重命名疗程
	 */
	var onSaveRenameCourse = function(){
		var data = $(this).data("params");
		var className = $(this).data("className");
		var libraryId = $("#courseLibirayTab select").val();
		var courseId = $(this).attr("courseId");
		var name = $(this).parents("form").find("input[name=name]").val();
		var days = $(this).parents("form").find("input[name=days]").val();
		var reg1 = /\S/;
		var reg2 = /^[1-9][0-9]*$/;
		if( !reg1.test(name) ){
			$bb.toastShow("请输入疗程名称！");
		}else if( !reg2.test(days) ){
			$bb.toastShow("疗程天数请输入整数！");
		}else{
			var params = {
				"libraryId":libraryId,
			    "courseName":name,
			    "courseTotal":days.toString(),
			    "courseId":courseId,	// 空为修改
			};
			$servers.ajaxCourseModify(params,saveCourseCallBack,libraryId,className);
		}
	};

	/**
	 * 重命名疗程模态框
	 */
	var onRenameCourse = function(){
		$("#context-menu").removeClass("open");
		var data = $(this).data();
		$servers.ajaxCoursebasic(data.refId,function(req){
			var className = "addNodeModal";
			$comm.modal({
				"className":className,
				"tit":"疗程重命名"
			},function(){
				$ui.addCourseFormInit({
					"dom":$("." + className + " .modal-body"),
					"data":req
				});
				$("." + className).modal("show");
				$("#addCourseBtn").unbind("click");
				$("#addCourseBtn").data({"params":data,"className":className});
				$("#addCourseBtn").click(onSaveRenameCourse);
			});
		});
	}

	/**
	 * 添加疗程
	 */
	var onSaveAddCourse = function(){
		var data = $(this).data("params");
		var className = $(this).data("className");
		var libraryId = $("#courseLibirayTab select").val();
		var name = $(this).parents("form").find("input[name=name]").val();
		var days = $(this).parents("form").find("input[name=days]").val();
		var desc = $(this).parents("form").find("input[name=desc]").val();
		var remark = $(this).parents("form").find("input[name=remark]").val();
		var params = {
			"libraryId":libraryId,
			"ctypeId":data.id,	
		    "courseName":name,
		    "courseTotal":days.toString(),
		    "courseDesc":desc,
		    "remark":remark,
		};
		$servers.ajaxCourseModify(params,saveCourseCallBack,libraryId,className);
	}

	/**
	 * 添加疗程模态框
	 */
	var onAddCourse = function(){
		$("#context-menu").removeClass("open");
		var data = $(this).data();
		var className = "addNodeModal";
		$comm.modal({
			"className":className,
			"tit":"添加疗程"
		},function(){
			$ui.addCourseFormInit({
				"dom":$("." + className + " .modal-body"),
			});
			$("." + className).modal("show");
			$("#addCourseBtn").unbind("click");
			$("#addCourseBtn").data({"params":data,"className":className});
			$("#addCourseBtn").click(onSaveAddCourse);
		});
	}

	/**
	 * 请求删除疗程成功后的回调函数
	 */
	var ajaxCourseDelCallBack = function(data){
		$bb.toastShow('删除成功',1500);
		var libraryId = $("#courseLibirayTab select").val();
		onCourseChange(libraryId);
	}
	/**
	 * 请求拷贝疗程成功后的回调函数
	 */
	var ajaxCourseCloneCallBack = function(data,libraryId,className){
		$bb.toastShow('拷贝成功',1500);
		$("." + className).modal("hide");
		onCourseChange(libraryId,data);
	}
	

	/**
	 * 删除疗程
	 */
	var onRemoveCourse = function(){
		$("#context-menu").removeClass("open");
		var courseId = $(this).data("refId");
		var params = {
			"params":courseId,
			"callBack":ajaxCourseDelCallBack
		}
		$bb.toastConfirmShow($servers.ajaxCourseDel,params,"您确定删除该疗程库吗？");
	}
	/**
	 * 拷贝疗程
	 */
	var onCopyCourse = function(){
		$("#context-menu").removeClass("open");
		var courseId = $(this).data("refId");
		var className = $(this).data("className");
		var libraryId = $("#courseLibirayTab select").val();
		var params = {
			"courseId":courseId,
			"className":className,
			"libraryId":libraryId,
			"callBack":ajaxCourseCloneCallBack
		}
		$bb.toastConfirmShow($servers.ajaxCourseClone,params,"您确定拷贝该疗程库吗？");
	}
	/**
	 * 右键：右键菜单的样式，定位，显示
	 */
	var menuRightClick = function(event,flag){
		var mouseX = event.originalEvent.x || event.originalEvent.layerX || 0; 
		var mouseY = event.originalEvent.y || event.originalEvent.layerY || 0;
		// 疗程分类右键菜单：courseClassify; 疗程右键菜单：course; 空白处：blank
		$ui.contextMenu({
			"id":"context-menu",
			"flag":flag
		});
		$("#context-menu").css({
			"position": "absolute",
		    "zIndex": 9999,
		    "top": mouseY + 'px',
		    "left": mouseX + 'px',
		}).addClass("open");
		$(document).click(function(){
			$("#context-menu").removeClass("open");
		});
		$("#context-menu").click(function(event){
			event.stopPropagation();
		});
	}

	/**
	 * ztree 相关回调函数
	 */
	var $ztree = {
		// 禁止拖拽
		beforeDrag: function(treeId,treeNodes){
			return false;
		},
		// 右键疗程不出现菜单
		beforeRightClick: function(treeId,treeNode){
			return true;
		},
		onRightClick: function(event,treeId,treeNode){
			if(treeNode != null){
				if(treeNode.isLeaf == "1"){
					menuRightClick(event,"course"); // course 疗程的右键菜单
					// 重命名（疗程）
					$("#context-menu .rename").unbind("click");
					$("#context-menu .rename").data({"refId":treeNode.refId});
					$("#context-menu .rename").click(onRenameCourse);
					// 删除（疗程）
					$("#context-menu .remove").unbind("click");
					$("#context-menu .remove").data({"refId":treeNode.refId});
					$("#context-menu .remove").click(onRemoveCourse);
					
					// 拷贝（疗程）
					$("#context-menu .copy").unbind("click");
					$("#context-menu .copy").data({"refId":treeNode.refId});
					$("#context-menu .copy").click(onCopyCourse);
				}else{
					menuRightClick(event,"courseClassify"); // courseClassify 疗程分类的右键菜单
					// 重命名（分类的重命名）
					$("#context-menu .rename").unbind("click");
					$("#context-menu .rename").data({"classify":"3","pId":treeNode.pId,"id":treeNode.id,"name":treeNode.name});
					$("#context-menu .rename").click(onModifyCourseClassify);
					// 添加根分类
					$("#context-menu .addRootClassify").unbind("click");
					$("#context-menu .addRootClassify").data({"classify":"1","pId":treeNode.pId});
					$("#context-menu .addRootClassify").click(onModifyCourseClassify);
					// 添加子分类
					$("#context-menu .addSubClassify").unbind("click");
					$("#context-menu .addSubClassify").data({"classify":"2","pId":treeNode.id});
					$("#context-menu .addSubClassify").click(onModifyCourseClassify);
					// 添加疗程
					$("#context-menu .addCourse").unbind("click");
					$("#context-menu .addCourse").data({"id":treeNode.id});
					$("#context-menu .addCourse").click(onAddCourse);
					// 删除（分类）
					$("#context-menu .remove").unbind("click");
					$("#context-menu .remove").data({"id":treeNode.id});
					$("#context-menu .remove").click(onRemoveCourseClassify);
					// 拷贝（疗程）
					$("#context-menu .copy").unbind("click");
					$("#context-menu .copy").data({"id":treeNode.id});
					$("#context-menu .copy").click(onCopyCourse);
				}
			}
		},
		beforeClick: function(treeId,treeNode,clickFlag){
			return true;
		},
		onClick: function(event,treeId,treeNode){
			if(treeNode && treeNode.isLeaf && treeNode.isLeaf == "1"){
				hasCourseRightStyle();
				$servers.ajaxCoursebasic(treeNode.refId,ajaxCoursebasicCallBack);
			}else{
				var str = "该疗程库还未有疗程，请右击左边的疗程分类或下面的按钮添加";
				$(".course-null .tip-null").html(str);
				courseNullRightStyle();
			}
		}
	};

	/**
	 * 疗程库里没有疗程时，右击疗程库空白处 添加分类、疗程节点
	 */
	var courseNullContextmenu = function(){
        $('#ztreeCourseLibirayWrap').contextmenu(function(){
        	return false;
        });
        $('#ztreeCourseLibiray').mousedown(function(event){
        	if (3 == event.which) {   //右键为3
                event.stopPropagation();
            } 
        });
        $("#ztreeCourseLibirayWrap").mousedown(function(event) {
            if (3 == event.which) {   //右键为3
                menuRightClick(event,"blank"); // course 疗程的右键菜单
                // 添加根分类
				$("#context-menu .addRootClassify").unbind("click");
				$("#context-menu .addRootClassify").data({"classify":"1"});
				$("#context-menu .addRootClassify").click(onModifyCourseClassify);
				// 添加疗程
				$("#context-menu .addCourse").unbind("click");
				$("#context-menu .addCourse").click(onAddCourse);
            } 
        });
	}

	/**
	 * 疗程库里没有疗程时，样式问题
	 */
	var courseNullRightStyle = function(){
        $("#courseInfo").css({"display":"none"});
        $(".food-library .panel-body").css({"height":"662px"});
        $(".course-null").css({"display":"block"});
        $("#courseFood,#courseNutrients").css({"display":"none"});
        // 添加根分类
		$(".course-null .add-root-classify").unbind("click");
		$(".course-null .add-root-classify").data({"classify":"1"});
        $(".course-null .add-root-classify").click(onModifyCourseClassify);
        // 添加疗程
		$(".course-null .add-course").unbind("click");
		$(".course-null .add-course").click(onAddCourse);
	}

	/**
	 * 疗程库里存在疗程时，样式问题
	 */
	var hasCourseRightStyle = function(){
		$("#courseInfo").css({"display":"block"});
        $(".food-library .panel-body").css({"height":"617px"});
        $(".course-null").css({"display":"none"});
        $("#courseFood,#courseNutrients").css({"display":"block"});
	}

	/**
	 * 查询疗程库菜单成功后的回调函数
	 */
	var ajaxCourseMenusCallBack = function(data,req){
		$ui.courseLibirayWrap({
			"id":"ztreeCourseLibirayWrap",
			"list":data
		});
		if(data.length == 0){
			// 点击疗程库空白处 添加分类、疗程节点
	        courseNullContextmenu();
	        // 没有疗程的情况
	        courseNullRightStyle();
		}else{
	        hasCourseRightStyle();
		    var setting = {
		    	view: {
					selectedMulti: false,
				},
				edit: {
					enable: true,
					showRemoveBtn: false,
					showRenameBtn: false,
				},
		    	data: {
		    		keep: {
						leaf: true,
						parent: true
					},
					simpleData: {
						enable: true
					}
				},
				callback: {
					beforeDrag: $ztree.beforeDrag,
					beforeRightClick: $ztree.beforeRightClick,
					onRightClick: $ztree.onRightClick,
					beforeClick: $ztree.beforeClick,
					onClick: $ztree.onClick
				}
		    };
		    var treeObj = $.fn.zTree.init($("#ztreeCourseLibiray"),setting,data);

		    treeObj.expandAll(true); // 全展开
		    // 初始化时，右边显示数据里的第一个叶子
		    var leafNode = [];
		    for (var i = 0; i < data.length; i++) {
		    	if( data[i].isLeaf == "1" ){
		    		leafNode.push( data[i].id );
		    	} 
		    }
		    var nodeId = req ? $servers.getNodeId(data,req) : leafNode[0];
		    var node = treeObj.getNodeByParam('id', nodeId); 
	        treeObj.selectNode(node);//选择点  
	        treeObj.setting.callback.onClick(null,treeObj.setting.treeId,node);//调用事件
        }
    }

    /**
	 * 选择疗程库
	 */
	var onCourseChange = function(libraryId,data){
        $servers.ajaxCourseMenus(libraryId,ajaxCourseMenusCallBack,data);
	}
	event.onCourseChange = function(){
		var libraryId = $(this).val();
        onCourseChange(libraryId);
	}

	/**
	 * 疗程某时段食物增加、修改 成功后的回调函数
	 */
	var ajaxCourseFoodModifyCallBack = function(data,courseVersionId){
		$servers.ajaxCourseNutrients(courseVersionId,ajaxCourseNutrientsCallBack);
	}

	/**
	 * 拖拽食品
	 */
	var $foodZtree = {
		beforeDrag: function(treeId,treeNodes){
			return treeNodes[0].isLeaf == "1" ? true : false;
		},
		onDrop: function(e,treeId,treeNodes,targetNode,moveType){
			var domClass = "food-name";
			// 判断是否拖曳在目标元素(domClass:food-name)里
			if( moveType == null && e.target.className == domClass ){
				var courseVersionId = $("#courseFood table").attr("courseVersionId");
				var periodId = $(e.target).attr("periodId");
				var params = {
				    "courseVersionId":courseVersionId,
				    "periodId":periodId,	
				    "foodId":treeNodes[0].refId
				}
				$servers.ajaxCourseFoodModify(params,ajaxCourseFoodModifyCallBack);
			}else{
				$bb.toastShow("放错了...请选择正确的位置！");
			}
		}
	};

	/**
	 * 查询食品库菜单成功后的回调函数
	 */
	var ajaxFoodMenusCallBack = function(data){
	    var setting = {
	    	view: {
				selectedMulti: false
			},
			edit: {
				enable: true,
				showRemoveBtn: false,
				showRenameBtn: false,
				drag: {
					isCopy: true,
					isMove: false
				}
			},
	    	data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				beforeDrag: $foodZtree.beforeDrag,
				onDrop: $foodZtree.onDrop
			}
	    };
	    $.fn.zTree.init($("#ztreeFoodLibiray"),setting,data);
	}

	/**
	 * 食品库
	 */
	var onfoodLibirayChange = function(foodLibraryId){
		$servers.ajaxFoodMenus(foodLibraryId,ajaxFoodMenusCallBack);
	}
	event.onfoodLibirayChange = function(){
		var foodLibraryId = $(this).val();
		onfoodLibirayChange(foodLibraryId);
	}

	return event;
});